#include <d3d9.h>
#include <d3dx9.h>
#include "World.h"
#include "Cube.h"
#include "Constants.h"

// Constructor
Minicraft::World::World()
{
	// Get a random starting hieght
	int randHeight = (rand() % HEIGHT) + 1;

	// Creates a cube for each slot in the world
	for(int x = 0; x < WIDTH; x++)
		for(int z = 0; z < DEPTH; z++)
		{
			// For each column, get a random height which is +/- 1 of the last column
			int newHeight = rand() % 3;
			if(newHeight == 0)
			{
				if(randHeight > 1)
					randHeight -= 1;
			}
			else if(newHeight == 1)
			{
				if(randHeight < HEIGHT)
					randHeight += 1;
			}
			int count = randHeight;
				
			for(int y = 0; y < HEIGHT; y++)
			{
				D3DXMATRIX cube = D3DXMATRIX();
				D3DXMatrixIdentity(&cube);
				D3DXMatrixTranslation(&cube, x*Minicraft::Constants::CUBESIZE, y*Minicraft::Constants::CUBESIZE, z*Minicraft::Constants::CUBESIZE);
				theWorld[x][y][z] = new Minicraft::Cube(cube);
				// makes bottom layers dirt
				if(count > 1)
				{
					theWorld[x][y][z]->SetType(Minicraft::CubeType::Dirt);
					count--;
				}
				// makes top layer grass
				else if(count == 1)
				{
					theWorld[x][y][z]->SetType(Minicraft::CubeType::Grass);
					count--;
				}
				// makes the rest air
				else
				{
					theWorld[x][y][z]->SetType(Minicraft::CubeType::Air);
					count--;
				}
			}
		}
}

// Deconstructor
// Deletes all the cubes
Minicraft::World::~World()
{
	for(int x = 0; x < WIDTH; x++)
		for(int y = 0; y < HEIGHT; y++)
			for(int z = 0; z < DEPTH; z++)
				delete theWorld[x][y][z];
}

// Links all the appropiate faces in the world's cubes
void Minicraft::World::LinkFaces()
{
	//for(int x = 0; x < WIDTH; x++)
	//	for(int y = 0; y < HEIGHT; y++)
	//		for(int z = 0; z < DEPTH; z++)

}

// Draw Method
// Draws each cube's draw method.
void Minicraft::World::Draw()
{
	for(int x = 0; x < WIDTH; x++)
		for(int y = 0; y < HEIGHT; y++)
			for(int z = 0; z < DEPTH; z++)
				theWorld[x][y][z]->Draw();
}